package com.sinosoft.vaccinetoai.security.shiro;

import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.iherus.shiro.cache.redis.RedisCacheManager;
import org.iherus.shiro.cache.redis.RedisSessionDAO;
import org.iherus.shiro.cache.redis.connection.RedisConnectionFactory;
import org.iherus.shiro.redis.spring.boot.autoconfigure.ShiroRedisProperties;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Optional;

/**
 * Shiro缓存配置
 * @author xzh
 * @date 2023-04-08 14:49
 * @since 1.0.0
 */
@ConditionalOnProperty(name = "shiro.redis.cache.enabled", matchIfMissing = false)
@EnableConfigurationProperties(ShiroRedisProperties.class)
@Configuration
public class CustomCacheConfig {

    /**
     * 缓存管理器
     * @param connectionFactory Redis连接工厂
     * @param properties 缓存配置属性
     * @return {@link CacheManager }
     * @author xzh
     * @since 1.0.0
     */
    @Bean("shiroCacheManager")
    public CacheManager cacheManager(RedisConnectionFactory connectionFactory, ShiroRedisProperties properties) {
        RedisCacheManager cacheManager = new RedisCacheManager();
        cacheManager.setConnectionFactory(connectionFactory);
        cacheManager.setKeyPrefix(properties.getCache().getKeyPrefix());
        cacheManager.setExpiration(properties.getCache().getExpiration());
        cacheManager.setScanBatchSize(properties.getCache().getBatchOptions().getScanBatchSize());
        cacheManager.setFetchBatchSize(properties.getCache().getBatchOptions().getFetchBatchSize());
        cacheManager.setDeleteBatchSize(properties.getCache().getBatchOptions().getDeleteBatchSize());

        Optional.ofNullable(properties.getCache().getDatabase()).ifPresent(cacheManager::setDatabase);
        return cacheManager;
    }


    /**
     * Session数据访问对象
     * @param cacheManager 缓存管理器
     * @return {@link SessionDAO }
     * @author xzh
     * @since 1.0.0
     */
    @Bean("redisSessionDAO")
    public SessionDAO sessionDAO(@Qualifier("shiroCacheManager") CacheManager cacheManager) {
        return new RedisSessionDAO(cacheManager);
    }
    
}
